package com.xzy.controller;

import com.xzy.pojo.TopicVote;
import com.xzy.pojo.VoteUser;
import com.xzy.service.TopicVoteService;
import com.xzy.service.VoteUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class VoteUserController {
    @Autowired
    VoteUserService voteUserService;

    @RequestMapping("/")
    public String login(){
        return "login";
    }
    @RequestMapping("/user/login")
    public String login(String username, String password, Model model){
//        得到当前用户对象，并进行封装到令牌中
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
            return "index";
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }
    @RequestMapping("/toRegister")
    public String  toRegister(){
        return "register";
    }
    @RequestMapping("/register")
    public String  register(String username,String password,Model model){
        try {
            int res=this.voteUserService.insertVoteUser(username,password);
            if(res>0){
                model.addAttribute("msg","注册用户成功");
                return "forward:/";
            }else {
                model.addAttribute("registerMsg","注册用户失败，用户已存在");
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return "register";
    }
//    没权限访问页面
    @RequestMapping("/noAuth")
    public String noAuth(){
        return "noAuth";
    }
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }

}
